const express = require('express');
const router = express.Router();
const sqlFn = require('../mysql')
const remove = require("loadsh/remove");
/**
 * @swagger
 * tags:
 *   - name: User
 *     description: 用户管理接口
 */

/**
 * @swagger
 * /user/add:
 *   post:
 *     summary: 添加新用户
 *     description: 添加新的用户到数据库中，并检查用户名是否存在。
 *     tags: [User]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *                 description: 用户姓名
 *                 example: "John Doe"
 *               account:
 *                 type: string
 *                 description: 用户账号
 *                 example: "johndoe"
 *               area:
 *                 type: string
 *                 description: 用户所在区域
 *                 example: "New York"
 *               tel:
 *                 type: string
 *                 description: 联系电话
 *                 example: "123456789"
 *               email:
 *                 type: string
 *                 description: 邮箱地址
 *                 example: "john.doe@example.com"
 *               picture:
 *                 type: string
 *                 description: 头像 URL
 *                 example: "/images/johndoe.png"
 *     responses:
 *       200:
 *         description: 用户添加成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   description: 返回状态码
 *                   example: 200
 *                 success:
 *                   type: boolean
 *                   description: 操作是否成功
 *                   example: true
 *       400:
 *         description: 用户名已存在
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   description: 返回状态码
 *                   example: -1
 *                 message:
 *                   type: string
 *                   description: 错误提示信息
 *                   example: "用户名已存在"
 */
router.post('/add', (req, res, next) => {
    const sql = 'select * from user where locate(?,account)>0'
    sqlFn(sql, [req.body.account], (err, data) => {
        if (err) {
            next(err)
            return
        }
        if (data && data.length) {
            res.send({code: -1, message: '用户名已存在'})
        } else {
            const sql = 'insert into user (name, account, area, tel, email, picture,relatedMenus) VALUES (?, ?, ?, ?, ?, ?,?)';
            const {name, account, area, tel, email, picture,relatedMenus} = req.body;
            console.log(req.body)
            sqlFn(sql, [name, account, area, tel, email, picture,relatedMenus], (err, data) => {
                if (err) {
                    next(err)
                    return
                }
                if (data.affectedRows) {
                    res.send({code: 200, success: true})
                }
            })
        }
    })
})
/**
 * @swagger
 * /user/list:
 *   get:
 *     summary: 获取用户列表
 *     description: 分页查询用户列表，并支持通过姓名进行模糊搜索。
 *     tags: [User]
 *     parameters:
 *       - name: current
 *         in: query
 *         schema:
 *           type: integer
 *         description: 当前页码
 *         example: 1
 *       - name: pageSize
 *         in: query
 *         schema:
 *           type: integer
 *         description: 每页显示的数据条数
 *         example: 5
 *       - name: name
 *         in: query
 *         schema:
 *           type: string
 *         description: 根据用户姓名进行模糊搜索
 *         example: "John"
 *     responses:
 *       200:
 *         description: 返回用户列表数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   description: 返回状态码
 *                   example: 200
 *                 records:
 *                   type: array
 *                   description: 用户记录列表
 *                   items:
 *                     type: object
 *                     properties:
 *                       id:
 *                         type: integer
 *                         description: 用户 ID
 *                         example: 1
 *                       name:
 *                         type: string
 *                         description: 用户姓名
 *                         example: "John Doe"
 *                       account:
 *                         type: string
 *                         description: 用户账号
 *                         example: "johndoe"
 *                       area:
 *                         type: string
 *                         description: 用户区域
 *                         example: "New York"
 *                       tel:
 *                         type: string
 *                         description: 用户联系电话
 *                         example: "123456789"
 *                       email:
 *                         type: string
 *                         description: 用户邮箱
 *                         example: "john.doe@example.com"
 *                       picture:
 *                         type: string
 *                         description: 头像 URL
 *                         example: "/images/johndoe.png"
 *                 pagination:
 *                   type: object
 *                   properties:
 *                     pageSize:
 *                       type: integer
 *                       description: 每页显示的记录数
 *                       example: 5
 *                     total:
 *                       type: integer
 *                       description: 数据总量
 *                       example: 100
 *       400:
 *         description: 查询失败，返回错误提示信息。
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   description: 返回状态码
 *                   example: 400
 *                 message:
 *                   type: string
 *                   description: 错误提示信息
 *                   example: "查询失败"
 */
router.get('/list', (req, res, next) => {
    const { query } = req;
    const { current = 1, pageSize = 5 } = query;

    // 修正拼写错误: `form` -> `from`
    const countSql = `select COUNT(*) as num FROM user where account!='admin' ${req.query.name ? 'and locate(?, name) > 0' : ''}`;

    // 执行统计总数的SQL查询
    sqlFn(countSql, [query.name], (err, countData) => {
        if (err) {
            next(err);
            return;
        }
        const total = countData[0].num;

        // 修正拼写错误: `form` -> `from`
        const dataSql = `select * from user where account!='admin' ${req.query.name ? 'and locate(?, name) > 0' : ''} LIMIT ${(current - 1) * pageSize}, ${pageSize}`;

        // 执行分页查询的SQL查询
        sqlFn(dataSql, [req.query.name], (err, data) => {
            if (err) {
                next(err);
                return;
            }
            res.send({ code: 200, records: data, pagination: { pageSize, total } });
        });
    });
});
/**
 * @swagger
 * /update:
 *   post:
 *     summary: 更新用户信息
 *     description: 更新指定用户的详细信息（包括用户名、账号、地区、电话、邮箱和头像）。
 *     tags:
 *       - 用户管理
 *     parameters:
 *       - in: body
 *         name: user
 *         description: 要更新的用户信息
 *         schema:
 *           type: object
 *           required:
 *             - id
 *             - name
 *             - account
 *           properties:
 *             id:
 *               type: integer
 *               description: 用户ID
 *             name:
 *               type: string
 *               description: 用户名
 *             account:
 *               type: string
 *               description: 用户账号
 *             area:
 *               type: string
 *               description: 用户所在地区
 *             tel:
 *               type: string
 *               description: 用户电话
 *             email:
 *               type: string
 *               description: 用户邮箱
 *             picture:
 *               type: string
 *               description: 用户头像URL
 *     responses:
 *       200:
 *         description: 更新成功
 *         schema:
 *           type: object
 *           properties:
 *             code:
 *               type: integer
 *               description: 响应码
 *             success:
 *               type: boolean
 *               description: 是否更新成功
 *       500:
 *         description: 更新失败
 */

router.post('/update',function(req,res,next){
    const sql='update user set `name`=?,`account`=?,`area`=?,`tel`=?,`email`=? ,`picture`=? where `id`=?'
    const {name,account,area,tel,email,picture,id}=req.body
    sqlFn(sql,[name,account,area,tel,email,picture,id],function(err,data){
        if(err){
            next(err)
            return
        }
        if(data.affectedRows){
            res.send({code:200,success:true})
        }
    })
})
/**
 * @swagger
 * /delete:
 *   post:
 *     summary: 删除用户操作
 *     description: Deletes a user from the database by ID.
 *     tags:
 *       - User
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               id:
 *                 type: integer
 *                 description: The ID of the user to delete.
 *                 example: 123
 *     responses:
 *       '200':
 *         description: User deleted successfully
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: string
 *                   example: '00000'
 *                 success:
 *                   type: boolean
 *                   example: true
 *       '500':
 *         description: Internal Server Error
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 error:
 *                   type: string
 *                   example: 'Database error'
 */
router.post('/delete',function(req,res,next){
    const sql='delete from user where `id`=?'
    sqlFn(sql,[req.body.id],function(err,data){
        if(err){
            next(err)
            return
        }
        if(data.affectedRows){
            res.send({code:200,success:true})
        }
    })
})

/**
 * @swagger
 * /relateMenus:
 *   get:
 *     summary: 关联菜单
 *     description: Fetch a tree structure of menus where `isOfAdmin` is 2.
 *     tags:
 *       - User
 *     responses:
 *       200:
 *         description: A successful response containing the menu tree.
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 records:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       id:
 *                         type: integer
 *                         example: 1
 *                       name:
 *                         type: string
 *                         example: "Menu Name"
 *                       pid:
 *                         type: integer
 *                         example: 0
 *                       children:
 *                         type: array
 *                         items:
 *                           type: object
 *                           properties:
 *                             id:
 *                               type: integer
 *                               example: 2
 *                             name:
 *                               type: string
 *                               example: "Submenu Name"
 *                             pid:
 *                               type: integer
 *                               example: 1
 *                             children:
 *                               type: array
 *                               items:
 *                                 $ref: '#/components/schemas/Menu'  # You can define a schema for Menu if needed
 *       500:
 *         description: An internal server error occurred
 */

router.get('/relateMenus',(req,res,next)=>{
    const sql='select * from menu where `isOfAdmin`=2'
    sqlFn(sql,[],function(err,data){
        if(err){
            next(err)
            return
        }
        const getMenuTree = (menus = []) => {
            menus.map(item => {
                menus.map(menu => {
                    if (item.pid == menu.id) {
                        menu.children = menu.children || []
                        menu.children.push(item)
                    }
                })
            })
            remove(menus, (menu) => menu.pid != -1)
            return menus
        }
        res.send({code:200,records:getMenuTree(data)})
    })
})
/**
 * @swagger
 * /updateRelateMenus:
 *   post:
 *     summary: 修改菜单权限
 *     description: 根据用户ID修改其关联菜单权限
 *     tags:
 *       - User
 *     requestBody:
 *       description: 传递用户ID和要更新的菜单权限列表
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - id
 *               - relatedMenus
 *             properties:
 *               id:
 *                 type: integer
 *                 description: 用户ID
 *                 example: 1
 *               relatedMenus:
 *                 type: array
 *                 description: 关联的菜单权限列表
 *                 items:
 *                   type: string
 *                 example: ["menu1", "menu2", "menu3"]
 *     responses:
 *       200:
 *         description: 修改成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 success:
 *                   type: boolean
 *                   example: true
 *       400:
 *         description: 请求参数错误
 *       500:
 *         description: 服务器内部错误
 */
router.post('/updateRelateMenus',(req,res,next)=>{
    const sql='update user set `relatedMenus`=? where `id`=?'
    const {relatedMenus,id}=req.body
    sqlFn(sql,[relatedMenus,id],function(err,data){
        if(err){
            next(err)
            return
        }
        if(data.affectedRows){
            res.send({code:200,success:true})
        }
    })
})
module.exports = router
